// pages/set/index.js
import {
  Toast
} from 'tdesign-miniprogram';
import * as comm from '../../../utils/common';
const storageService = require('../../../services/storage')

function isNumber(value) {
  if (value == null || value == undefined || value.length == 0) {
    return false;
  }
  return !isNaN(value);
}

// 获取 App 实例
const appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

    activeValues: [],
    colors: [{
      cor: "#FFFFFF",
      nm: "白色"
    }, {
      cor: "#FFFACD",
      nm: "暖白"
    }, {
      cor: "#FFFF00",
      nm: "黄色"
    }, {
      cor: "#FFD700",
      nm: "金色"
    }, {
      cor: "#FF91AF",
      nm: "粉红"
    }, {
      cor: "#FF0000",
      nm: "红色"
    }, {
      cor: "#DC143C",
      nm: "深红"
    }, {
      cor: "#00FF7F",
      nm: "春绿"
    }, {
      cor: "#00FF00",
      nm: "绿色"
    }, {
      cor: "#228B22",
      nm: "暗绿"
    }, {
      cor: "#4169E1",
      nm: "宝蓝"
    }, {
      cor: "#0000FF",
      nm: "蓝色"
    }, {
      cor: "#00008B",
      nm: "深蓝"
    }, {
      cor: "#EE82EE",
      nm: "浅紫"
    }, {
      cor: "#FF00FF",
      nm: "紫红"
    }, {
      cor: "#800080",
      nm: "紫色"
    }],
    did: "",
    fanStartTemp: 50,
    ntcDiffTemp: 0,
    channels: [],

    popVisible: false,
    selCorIdx: -1,
    selChIdx: -1,
    chName: "",

    host: "www.99666666.xyz",
    port: 80,
    imgName: null,

    deviceCfg: {},
    deviceId: null,

    popConfirmVisible: false,
    popConfirmCont: "",
    popConfirmType: "",

    eabCh: false,
    eabTemp: false,

    verObj: {
      "t": "",
      "v": 0,
      "s": ""
    },

    verBtnName: "检查更新",

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    let chCfg = storageService.getDeviceChannels(options.did)
    let tempCfg = storageService.getTempInfo(options.did)
    let dobj = {};
    if (chCfg != null) {
      dobj.channels = chCfg;
    }
    if (!comm.isEmptyObj(tempCfg)) {
      dobj.fanStartTemp = tempCfg.fanStartTemp;
      dobj.ntcDiffTemp = tempCfg.ntcDiffTemp;
    }
    this.data.did = options.did;
    this.setData(dobj);
    let deviceObj = storageService.getDeviceInfo(options.did)
    this.data.deviceCfg = deviceObj;
    this.setData({
      deviceId: deviceObj.deviceId
    });
    if (deviceObj["eabCh"] == null || deviceObj["eabCh"] == 1) {
      this.setData({
        eabCh: true
      });
    }
    if (deviceObj["eabTemp"] == null || deviceObj["eabTemp"] == 1) {
      this.setData({
        eabTemp: true
      });
    }

    let tvobj = appInstance.deviceVerMap[this.data.did];
    if (!comm.isEmptyObj(tvobj)) {
      this.verObj = JSON.parse(JSON.stringify(tvobj));
      const ver = "V" + this.verObj.ver.substring(1)
      this.setData({
        verBtnName: `${this.data.verBtnName}(${ver})`
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  onGoBack() {
    wx.navigateBack({});
  },
  handleChange(e) {
    this.setData({
      activeValues: e.detail.value,
    });
  },
  ckChange(e) {
    let idx = e.currentTarget.dataset.idx;
    let oldV = this.data.channels[parseInt(idx)].u;
    let str = "channels[" + idx + "].u";
    this.setData({
      [str]: oldV == 1 ? 0 : 1
    });
  },
  showPop(e) {
    let idx = e.currentTarget.dataset.idx;
    let nm = this.data.channels[parseInt(idx)].nm;
    let cor = this.data.channels[parseInt(idx)].c;
    let selIdx = -1;
    for (var i = 0; i < this.data.colors.length; i++) {
      if (cor == this.data.colors[i].cor) {
        selIdx = i;
        break;
      }
    }
    this.setData({
      popVisible: true,
      chName: nm,
      selCorIdx: selIdx,
      selChIdx: idx
    });
  },
  closePop() {
    this.setData({
      popVisible: false
    });
  },
  confirmPop() {
    let str = "channels[" + this.data.selChIdx + "].nm";
    this.setData({
      popVisible: false,
      [str]: this.data.chName
    });
    if (this.data.selCorIdx >= 0) {
      let str1 = "channels[" + this.data.selChIdx + "].c";
      this.setData({
        popVisible: false,
        [str1]: this.data.colors[this.data.selCorIdx].cor
      });
    }


  },
  chNameChange(e) {
    this.setData({
      chName: e.detail.value
    });
  },
  selectCor(e) {
    let idx = e.currentTarget.dataset.idx;
    let oldIdx = this.data.selCorIdx;
    if (oldIdx >= 0) {
      if (idx == oldIdx) {
        this.setData({
          selCorIdx: -1
        });
      } else {
        this.setData({
          selCorIdx: idx
        });
      }
    } else {
      this.setData({
        selCorIdx: idx
      });
    }
  },
  saveChannel() {
    storageService.saveDeviceChannels(this.data.did, this.data.channels)
    let channels = [];
    for (var i = 0; i < this.data.channels.length; i++) {
      let chCfg = this.data.channels[i];
      if (chCfg.u == 0) {
        continue;
      }
      channels.push(chCfg);
    }
    let autoCfg = storageService.getAutoCfg(this.data.did)
    if (!comm.isEmptyObj(autoCfg)) {
      for (var j = 0; j < autoCfg.modes.length; j++) {
        let cls = autoCfg.modes[j].cls;
        let newCls = [];
        for (var i = 0; i < channels.length; i++) {
          let chObj = JSON.parse(JSON.stringify(channels[i]));
          chObj.s = [];
          for (var m = 0; m < cls.length; m++) {
            if (cls[m].n == chObj.n) {
              chObj.s = cls[m].s;
              break;
            }
          }
          newCls.push(chObj);
        }
        autoCfg.modes[j].cls = newCls;
      }
      storageService.saveAutoCfg(this.data.did, autoCfg)
    }

    let handCfg = storageService.getHandCfg(this.data.did)
    if (!comm.isEmptyObj(handCfg)) {
      for (var j = 0; j < handCfg.modes.length; j++) {
        let cls = handCfg.modes[j].cls;
        let newCls = [];
        for (var i = 0; i < channels.length; i++) {
          let chObj = {
            "n": channels[i].n,
            "nm": channels[i].nm,
            "c": channels[i].c,
            "v": 0
          };
          for (var m = 0; m < cls.length; m++) {
            if (cls[m].n == chObj.n) {
              chObj.v = cls[m].v;
              break;
            }
          }
          newCls.push(chObj);
        }
        handCfg.modes[j].cls = newCls;
      }
      storageService.saveHandCfg(this.data.did, handCfg)
    }
    this.showToast('保存成功!');
  },
  fanStartTempChange(e) {
    let v = e.detail.value;
    if (!isNumber(v)) {
      v = this.data.fanStartTemp;
    } else {
      v = parseInt(v);
      if (v < 25 || v > 60) {
        v = this.data.fanStartTemp;
      }
    }
    this.setData({
      fanStartTemp: v
    });
  },
  ntcDiffTempChange(e) {
    let v = e.detail.value;
    if (!isNumber(v)) {
      v = this.data.ntcDiffTemp;
    } else {
      v = parseInt(v);
      if (v < -5 || v > 5) {
        v = this.data.ntcDiffTemp;
      }
    }
    this.setData({
      ntcDiffTemp: v
    });
  },
  saveTemp() {
    const $t = this;
    setTimeout(() => { //防止参数值为生效
      storageService.saveTempInfo($t.data.did, {
        fanStartTemp: $t.data.fanStartTemp,
        ntcDiffTemp: $t.data.ntcDiffTemp
      })
      let pdata = {
        "st": appInstance.globalData.tempArr[$t.data.fanStartTemp + $t.data.ntcDiffTemp],
        "sp": appInstance.globalData.tempArr[$t.data.fanStartTemp + $t.data.ntcDiffTemp - 5],
        "b": $t.data.ntcDiffTemp
      };
      appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "updateTemp", pdata, function (error) {
        if (error) {
          $t.showToast("保存失败!" + error);
        } else {
          $t.showToast('保存成功!');
        }
      });
    }, 200);
  },
  hostChange(e) {
    let v = e.detail.value;
    this.setData({
      host: v
    });
  },
  portChange(e) {
    let v = e.detail.value;
    this.setData({
      port: v
    });
  },
  imgNameChange(e) {
    let v = e.detail.value;
    this.setData({
      imgName: v
    });
  },
  saveImg() {
    if (comm.isEmpty(this.data.host) || comm.isEmpty(this.data.port) || comm.isEmpty(this.data.imgName)) {
      this.showToast('参数错误!');
      return;
    }
    this.setData({
      popConfirmVisible: true,
      popConfirmCont: "确定要更新固件吗？更新过程中指示灯会快速闪烁并自动重启！",
      popConfirmType: "saveImg"
    });
  },
  resetDevice() {
    this.setData({
      popConfirmVisible: true,
      popConfirmCont: "重置设备将使设备恢复初始化，确认要重置设备吗？",
      popConfirmType: "reset"
    });
  },
  clearCache() {
    this.setData({
      popConfirmVisible: true,
      popConfirmCont: "确定要清理缓存数据吗？",
      popConfirmType: "clearCache"
    });
  },
  closePopDialog() {
    this.setData({
      popConfirmVisible: false
    });
  },
  confirmPopDialog() {
    const $t = this;
    if (this.data.popConfirmType == "reset") {
      $t["timeout_reset"] = setTimeout(() => {
        $t.showToast("发送重置命令失败!");
      }, 1000);
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "reset", null, function (error) {
        if (error) {
          $t.showToast("发送重置命令失败!" + error);
        } else {
          $t.showToast("发送重置命令成功!");
        }
        clearTimeout($t["timeout_reset"]);
      });
    } else if (this.data.popConfirmType == "clearCache") {
      storageService.removeAutoCfg(this.data.did)
      storageService.removeHandCfg(this.data.did)
      storageService.removeUpdownCfg(this.data.did)
      $t.showToast("清理完成!");
    } else if (this.data.popConfirmType == "saveImg") {
      $t["timeout_saveImg"] = setTimeout(() => {
        $t.showToast("发送更新固件命令失败!");
      }, 1000);
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "updateImg", {
        host: this.data.host,
        port: this.data.port,
        image: this.data.imgName
      }, function (error) {
        if (error) {
          $t.showToast("发送更新固件命令失败!" + error);
        } else {
          $t.showToast("发送更新固件命令成功!");
        }
        clearTimeout($t["timeout_saveImg"]);
      });

    }

    this.closePopDialog();
  },
  checkVersion() {
    if (!comm.isEmpty(this.data.imgName)) {
      this.saveImg();
      return;
    }
    let $t = this;
    comm.httpGet("/version/check?ver=" + $t.verObj.ver, function (res) {
      if (comm.isEmpty(res.data)) {
        $t.showToast("已经是最新版本！");
      } else {
        $t.showToast("有新版本可以更新！");
        $t.setData({
          verBtnName: "开始更新",
          imgName: res.data
        });
      }
    }, function (error) {
      console.log(error);
      $t.showToast("检查更新异常！");
    });
  },
  showToast(msg) {
    Toast({
      context: this,
      selector: '#t-toast',
      message: msg,
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
})